package com.lbm.business.web.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import com.lbm.baseclass.controller.LBMBaseController;
import com.lbm.baseclass.utils.Eryptogram;
import com.lbm.baseclass.utils.json.JsonUtil;
import com.lbm.business.service.IRoleInfoService;
import com.lbm.business.service.IRoleUserService;
import com.lbm.business.service.IUserInfoService;
import com.lbm.model.RoleInfo;
import com.lbm.model.RoleUser;
import com.lbm.model.UserInfo;

public class UserInfoController  extends LBMBaseController{
	private IUserInfoService userInfoService;
	private IRoleUserService roleUserService;
	private IRoleInfoService roleInfoService;
	public void setRoleInfoService(IRoleInfoService roleInfoService) {
		this.roleInfoService = roleInfoService;
	}

	public void setRoleUserService(IRoleUserService roleUserService) {
		this.roleUserService = roleUserService;
	}

	public void setUserInfoService(IUserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	/**
	* 用户列表
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv=new ModelAndView("WEB-INF/jsp/userinfo/userinfolist.jsp");
	    return mv;
	}
	/**
	* 加载用户列表数据
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView ajaxlist(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String hql="from UserInfo where 1=1";
		String userClass=request.getParameter("class");
		String userNote=request.getParameter("userNote");
		if(!isAdmin(request))hql+=" and userName ='"+getUser(request).getUserName()+"'";
		if(userClass!=null&&userClass!="")hql+=" and userClass like '%"+userClass+"%'";
		if(userNote!=null&&userNote!="")hql+=" and userNote like '%"+userNote+"%'";
		String sort=request.getParameter("sort");
		String order=request.getParameter("order");
		if(sort!=""&&sort!=null)hql+=" order by "+sort+" "+order;
		List<UserInfo> list=calcPage(request, userInfoService, hql);
		int total=userInfoService.getUserinfoByHQL(hql).size();
		String json="";
		json = "{\"total\": " + total + ", \"rows\": "
				+ JsonUtil.toString(list, JsonUtil.COLLECTION_FILTER) + "}";
		renderJson(response, json);
	    return null;
	}
	/**
	* 添加
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv=new ModelAndView("WEB-INF/jsp/userinfo/userinfoform.jsp");
		return mv;
	}
	/**
	* 分配角色
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView listRole(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("WEB-INF/jsp/userinfo/definerole.jsp");
		String userid=request.getParameter("id");
		List<RoleInfo> roles=roleInfoService.getAllRoleInfo();
		List<RoleUser> roleusers=roleUserService.getRoleUserByHQL("from RoleUser where userid='"+userid+"'");
		for(Iterator<RoleInfo> it = roles.iterator(); it.hasNext();){
			RoleInfo role = it.next();
			for(RoleUser temp : roleusers){
				if(temp.getRoleid().equals(role.getRoleid()))
					it.remove();
			}
		}
		List<RoleInfo> defiends=new ArrayList<RoleInfo>();
		for(RoleUser temp : roleusers){
			defiends.add(temp.getRoleInfo());
		}
		mv.addObject("roles", roles);
		mv.addObject("defiends", defiends);
		mv.addObject("userId", userid);
		return mv;
	}
	/**
	* 保存所分配角色
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView saveRoleSet(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		boolean flag=true;
		String ids=request.getParameter("ids");
		String userid=request.getParameter("userId");
		String[] roleids=ids.split(",");
		List<RoleUser> dataList=roleUserService.getRoleUserByHQL("from RoleUser where userid='"+userid+"'");
		roleUserService.deleteBatchVO(dataList);
		for(String temp : roleids){
			RoleUser ru=new RoleUser();
			ru.setRoleid(temp);
			ru.setUserid(userid);
			try {
				roleUserService.saveOrUpdateRoleUser(ru);
			} catch (Exception e) {
				log.error(e);
				flag=false;
			}
		}
		renderJson(response,toJson("success",flag));
		return null;
	}
	/**
	* 修改
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView modify(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv=new ModelAndView("WEB-INF/jsp/userinfo/userinfoform.jsp");
		UserInfo userinfo=userInfoService.getUserinfoById(request.getParameter("id"));
		mv.addObject("userInfo", userinfo);
		return mv;
	}
	/**
	* 删除
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		boolean flag=true;
		String id=request.getParameter("ids");
		String[] ids=id.split(",");
		for(int i=0;i<ids.length;i++){
			try {
				userInfoService.deleteUserinfo(ids[i]);
			} catch (Exception e) {
				log.error(e);
				flag=false;
			}
		}
		renderJson(response, toJson("success", flag));
		return null;
	}
	/**
	* 保存
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		boolean flag=true;
		String userid=request.getParameter("userid");
		String userName=request.getParameter("userName");
		String userNote=request.getParameter("userNote");
		String sex=request.getParameter("sex");
		String phone=request.getParameter("phone");
		String userClass=request.getParameter("userClass");
		UserInfo userinfo=userInfoService.getUserinfoById(userid);
		if(userinfo==null){
			userinfo=new UserInfo();
			userinfo.setUserPW(Eryptogram.getUserPasswd("123456"));
		}
		if(userid!=null&&userid!="")userinfo.setUserid(userid);
		if(userName!=null&&userName!="")userinfo.setUserName(userName);
		if(userNote!=null&&userNote!="")userinfo.setUserNote(userNote);
		if(sex!=null&&sex!="")userinfo.setSex(sex);
		if(phone!=null&&phone!="")userinfo.setPhone(phone);
		if(userClass!=null&&userClass!="")userinfo.setUserClass(userClass);
		try {
			userInfoService.saveOrUpdateUserinfo(userinfo);
		} catch (Exception e) {
			log.error(e);
			flag=false;
		}
		renderJson(response, toJson("success",flag));
		return null;
	}
	/**
	* 调用修改密码窗口
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView password(final HttpServletRequest request,final HttpServletResponse response)throws Exception
	{
		return new ModelAndView("WEB-INF/jsp/userinfo/userinfopassword.jsp");
	}
	/**
	* 保存修改密码
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView changePwd(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		boolean flag=false;
		String old=request.getParameter("oldpassword");
		String newpw=request.getParameter("newpassword");
		UserInfo user=userInfoService.getUserinfoById(getUserId(request));
		if(user!=null){
			if(Eryptogram.getUserPasswd(old).equals(user.getUserPW())){
				flag=true;
				user.setUserPW(Eryptogram.getUserPasswd(newpw));
				userInfoService.saveOrUpdateUserinfo(user);
			}
		}
		renderJson(response, toJson("success",flag));
		return null;
	}
	/**
	* 检查用户名是否已经存在
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView testUserName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String uname = request.getParameter("fieldValue");
		String fieldId = request.getParameter("fieldId");
		List<UserInfo> userinfo = userInfoService.getUserinfoByHQL("from UserInfo where userName='"+uname+"'");
		boolean flag=true;
		if(userinfo.size()!=0){
			flag= false;
		}
		renderJson(response, toJsArray(fieldId, flag ? "" + flag : "", "ajaxNameCall"));
		return null;
	}
	/**
	* 查看用户详细
	* @param request
	* @param response
	* @return
	* @throws Exception
	*/
	public ModelAndView view(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv=new ModelAndView("WEB-INF/jsp/userinfo/showuserinfo.jsp");
		String userid = request.getParameter("userid");
		List<RoleUser> list=roleUserService.getRoleUserByHQL("from RoleUser where userid='"+userid+"'");
		List<RoleInfo> roles=new ArrayList<RoleInfo>();
		for(RoleUser temp : list){
			roles.add(temp.getRoleInfo());
		}
		mv.addObject("roles", roles);
		mv.addObject("userid", userid);
		return mv;
	}
}
